package es.udc.fic.hamNeggs.manager;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import es.udc.fic.hamNeggs.pojo.Works;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Repository(value = "works")
public class WorksManager extends AbstractManager {
    private final static Logger LOG = Logger.getLogger(WorksManager.class.getName());

    @Transactional(readOnly = true)
    @SuppressWarnings("unchecked")
    public List<Works> getWorksList() {
        List<Works> list = session.createQuery("from Works").list();

        Collections.sort(list,
                new Comparator<Works>() {
                    public int compare(Works o1, Works o2) {
                        return o1.getProject().getId().intValue() - o2.getProject().getId().intValue();
                    }
                });

        return list;
    }

    @SuppressWarnings("unchecked")
    @Transactional(readOnly = true)
    public Works getWorks(Long user, Long project) {
        List<Works> works = getWorksList();
        for (Works work : works)
            if (work.getUser().getId().doubleValue() == user && work.getProject().getId().doubleValue() == project)
                return work;
        return null;
    }

    @Transactional(readOnly = false)
    public void saveWorks(Works works) {
        super.save(works, LOG);
    }

    @Transactional(readOnly = false)
    public void deleteWorks(Works works) {
        super.delete(works, LOG);
    }

    @Transactional(readOnly = false)
    public void updateWorks(Works works) {
        super.update(works, LOG);
    }
}
